package com.liuyk.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import java.util.Random;

/**
 * Messenger进程通讯
 * <p>
 * Created by liuyk on 2015/10/29.
 */
public class MessengerService extends Service implements Runnable {

    private static final String TAG = "MessengerService";

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), "Client: " + msg.getData().getString("msg"), Toast.LENGTH_LONG).show();
                    //服务端向客户端回复
                    Messenger client = msg.replyTo;
                    Message message = Message.obtain(null, 0);
                    Bundle data = new Bundle();
                    data.putString("reply", "收到消息，正在执行...");
                    message.setData(data);
                    try {
                        client.send(message);
                        exe();
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
    private final Messenger mMessenger = new Messenger(mHandler);

    private void exe() {
        new Thread(this).start();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    private void doFun() {
        final Random random = new Random();
        for (int i = 1; i < 20; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Log.i(TAG, "to do: " + random.nextInt(i) + "%");
        }
    }

    @Override
    public void run() {
        doFun();
    }

}
